﻿namespace IntellectShop.Web2.Hardware.Controllers
{
	using System;
	using System.Web;
	using System.Web.Mvc;
	using IntellectShop.Common;
	using IntellectShop.Web2.Hardware.ViewModels;

	[IntellectShop.Web2.Hardware.Code.NoCache]
	[IntellectShop.Web2.Hardware.Code.HandleErrorWithELMAH]
	[ValidateInputAttribute(false)]
	public class TagsController : Controller
	{
		public ActionResult Browse(string tag)
		{
			var singleTag = Common.SingleTag.RetrieveByTag(tag);
			if (singleTag == null)
				throw new HttpException(404, "Page not found");

			return View(new TagBrowseCommodityViewModel()
			{
				Tag = tag,
				Commodities = Common.SingleTag.RetrieveCommodities(tag)
			});
		}

		[Authorize(Roles = Globals.AdministratorRoleName)]
		public ActionResult Index()
		{
			var viewModel = new TagsViewModel
			{
				SingleTags = Common.SingleTag.RetrieveAll(),
			};

			return View(viewModel);
		}

		[Authorize(Roles = Globals.AdministratorRoleName)]
		public ActionResult Edit(string tag)
		{
			var singleTag = Common.SingleTag.RetrieveByTag(tag);
			if (singleTag == null)
				throw new HttpException(404, "Page not found");

			return View(singleTag);
		}

		[HttpPost]
		[Authorize(Roles = Globals.AdministratorRoleName)]
		public ActionResult Edit(string tag, FormCollection collection)
		{
			var singleTag = Common.SingleTag.RetrieveByTag(tag);
			if (singleTag == null)
				throw new HttpException(404, "Page not found");

			try
			{
				if (!ModelState.IsValid)
					throw new ArgumentException("Ошибка при заполнении полей для: Tag!");

				UpdateModel(singleTag);
				singleTag.Update();
				return RedirectToAction("Index");
			}
			catch
			{
				return View(singleTag);
			}
		}

		[Authorize(Roles = Globals.AdministratorRoleName)]
		public ActionResult Delete(string tag)
		{
			try
			{
				if (!ModelState.IsValid)
					throw new ArgumentException("Ошибка при заполнении полей для: Tags!");

				Common.SingleTag.Delete(tag);
				return RedirectToAction("Index");
			}
			catch (Exception e)
			{
				var viewModel = new TagsViewModel
				{
					SingleTags = Common.SingleTag.RetrieveAll(),
					Message = e.Message
				};

				return View(viewModel);
			}
		}
	}
}
